<template>
  <div>
    <!-- 导航栏 -->
    <div>
      <nav-bar>
      <template #left>
        <van-icon name="arrow-left" @click="$router.push('/layout/home')"/>
      </template>
    </nav-bar>
    </div>
         <!-- 输入框容器 -->
    <div class="login-filed">
      <!-- 表单 -->
      <van-form
      ref='loginForm'
      @failed="onFailed"
      @submit="onLogin"
      :show-error-message='false'
      :show-error='false'
      validate-first
      >
                <van-cell-group>
          <!-- 手机号,必填项 -->
        <van-field
          v-model="userInfo.mobile"
          icon-prefix="toutiao"
          left-icon="shouji"
          placeholder="请输入手机号"
          center
          name='mobile'
          :rules="loginFormRules.mobile"
          autocomplete
  />
          <!-- 验证码必填项 -->
        <van-field
    center
    v-model="userInfo.code"
    icon-prefix="toutiao"
    left-icon="yanzhengma"
    placeholder="请输入验证码"
    :rules="loginFormRules.code"
    name='code'
  >
   <template #button>
     <van-count-down :time="1000 * 60" format="ss s" v-if="isShowCountDown" @finish="isShowCountDown=false"/>
    <van-button size="small"
    round
    v-else
    @click.prevent="sendCode"
    loading-type="spinner"
    :loading='isShowSendCodeLoading'
    >获取验证码</van-button>
  </template>
        </van-field>
          </van-cell-group>
          <!-- 登录按钮 -->
             <div class="login-button">
        <van-button type="info" block native-type="submit">登录</van-button>
    </div>
      </van-form>
    </div>
    <!-- 隐私条款 -->
    <div class="privacy-policy">隐私条款</div>
  </div>
</template>

<script>
//  components
import NavBar from 'components/NavBar'
//  axios
import { login, getCode } from 'network/user'
// vuex
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  components: { NavBar },
  data () {
    return {
      userInfo: {
        // 手机号
        mobile: '',
        // 验证码
        code: ''
      },
      // 登录表单验证规则
      loginFormRules: {
        mobile: [
          { required: true, message: '用户名不能为空' },
          { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号格式不对' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          { pattern: /^\d{6}$/, message: '验证码必须为6位数字' }
        ]
      },
      // 是否显示loading条
      isShowSendCodeLoading: false,
      // 是否显示倒计时
      isShowCountDown: false
    }
  },
  methods: {
    ...mapMutations(['setUserState']),
    // 表单效验成功触发的函数
    async onLogin () {
      if (!navigator.onLine) {
        return this.$toast.fail('您好像没有网络o(╯□╰)o')
      }
      this.$toast.loading({
        message: '登录中',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data: res } = await login(this.userInfo)
        // 请求成功保存token
        console.log(res)
        this.setUserState(res)
        this.$toast.success('登录成功')
        this.$router.push('/layout/home')
      } catch (err) {
        console.dir(err)
        this.$toast.fail('登录失败,用户名或密码错误')
      }
    },
    // 表单效验失败触发的函数
    onFailed (errorInfo) {
      if (errorInfo.errors[0]) {
        this.$toast({
          message: errorInfo.errors[0].message,
          position: 'top'
        })
      }
    },
    // 发送验证码
    /*  逻辑:1.先验证手机号格式对不对,对的话在进行发送验证码
          2.验证码发送之后,搞一个60s的倒计时
          3.还要考虑到用户网络卡的情况,所以点击发送验证码之后要弄一个loading,防止用户重复点击 */
    async sendCode () {
      try {
        await this.$refs.loginForm.validate('mobile')
        // 效验通过后前端直接搞loading加载,免得网络卡顿用户又重新点击
        this.isShowSendCodeLoading = true
        // 这里没必要接受返回的值,处理错误就行了,因为没出错,肯定是收到验证码了
        const result = await getCode(this.userInfo.mobile)
        console.log(result)
        // 短信发出去了,加载条要关掉
        this.isShowSendCodeLoading = false
        // 显示倒计时
        this.isShowCountDown = true
      } catch (err) {
        console.dir(err)
        if (err && !err.response && err.message) {
          this.$toast({
            message: err.message,
            position: 'top'
          })
        } else if (err && err.response.status === 404) {
          this.$toast({
            message: '手机号格式不正确',
            position: 'top'
          })
        } else if (err && err.response.status === 429) {
          this.$toast({
            message: '点的太快了,休息一会吧',
            position: 'top'
          })
        } else {
          this.$toast({
            message: '服务异常,请稍后再试',
            position: 'top'
          })
        }
        this.isShowSendCodeLoading = false
      }
    }
  }
}
</script>

<style lang='less' scoped>
  .login-filed{
    padding-top: 46px;
    .van-cell-group{
      min-height: 91px !important;
    }
    .van-button{
      font-size: 11px;
      color: #666666;
      background-color: #ededed;
      position: relative;
      &::before{
        content: "";
        position: absolute;
        width: 1px;
        height: 23px;
        background-color: #eee !important;
        left: -10px;
        z-index: 9;
        border: none;
        opacity: 1;
      }
    }
  }
  .login-button{
    padding: 27px 14px 0 14px;
    .van-button{
      font-size: 15px;
      color: #ffffff;
      border-radius: 3px;
      background-color: #6db4fb;
      border: none;
    }
  }
  .privacy-policy{
     position: fixed;
     bottom: 27px;
     left: 0;
     right: 0;
     text-align: center;
     color: #666666;
     font-size: 13px;
  }

</style>
